package a66weding.com.jiehuntong.activity.home.hotel.hotelnew;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.xutils.common.util.DensityUtil;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.ForSearchActivity;
import a66weding.com.jiehuntong.activity.home.hotel.HomeTaocanFragment1;
import a66weding.com.jiehuntong.activity.home.hotel.shop.HomeProductdetailActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.GoodShopBean;
import a66weding.com.jiehuntong.beans.HomeBotomListBean;
import a66weding.com.jiehuntong.beans.HomeHeaderLooperBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.ImageOptionsUtil;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.widgets.horizontal.HorizontalListView;
import a66weding.com.jiehuntong.widgets.horizontal.HorizontalListViewAdapter;

/**
 * Created by admin on 2016/9/11.
 */
public class HomeHotelActivity2 extends FragmentActivity implements OnNetResultListener,View.OnClickListener{
    private ViewPager viewpager;
    private TabLayout tabLayout;
    private int categoryId;
    private String title;
    private ViewGroup mContentLay;
    private LinearLayout mProgressLay;
    private LinearLayout mNoNetLay;
    //是否登录
    private boolean islogin;
    //会员id
     private int memBerId;
    //标示常量
    private static final int LOOPERDATA=3;
    private static final int HAVDDATA=7;
    private List<GoodShopBean.DataBean> goodshopListData;
    //轮播
    private ViewPager mLooperVp;
    private  LinearLayout mTopLooperLay;
    private   ImageView mRedpoint;
    private ImgAdapter imgAdapter;
    private static final int TOPVIEWSCROLL=1;
    private List<ImageView> mPointList;
    private int maxCount=5000;
    private List<HomeHeaderLooperBean.DataBean> looperDataDataListData;
    private int distance=DensityUtil.dip2px( 6)*2;
    private int px = DensityUtil.dip2px(6);
    private String mReturn = "";
    private TextView mReturnTv;
    public static int getAttentionRes=5;
    //推荐的店铺
    private HorizontalListView  horList;
    private HorizontalListViewAdapter adapter;
    //返回键
    private LinearLayout llay_header_back;
    //搜索
    private LinearLayout lay_header_rightfunc;
    //推荐好店
    private LinearLayout mHorizontallay;
    private boolean isShowError;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newproduct);
        Intent intent = getIntent();
        if (intent!=null){
            title = intent.getStringExtra("title");
            categoryId= intent.getIntExtra("categoryId",1081);
            mReturn = intent.getStringExtra("return");
        }
        initView();
        getdata();
    }

    private  void  initView(){
        lay_header_rightfunc = (LinearLayout) findViewById(R.id.lay_header_rightfunc);
        lay_header_rightfunc.setOnClickListener(this);
        llay_header_back = (LinearLayout) findViewById(R.id.llay_header_back);
        llay_header_back.setOnClickListener(this);
        mContentLay = (ViewGroup) findViewById(R.id.coolay_content);
        mNoNetLay = (LinearLayout) findViewById(R.id.lay_shoplist_nonet);
        mProgressLay = (LinearLayout) findViewById(R.id.progressLay);
        mReturnTv = (TextView) findViewById(R.id.tv_header_backcontent);
        TextView titleTv = (TextView) findViewById(R.id.tv_header_title);
        mReturnTv.setText(mReturn);
        if(!TextUtils.isEmpty(title)){
            titleTv.setText(title);
        }
        //轮播:
        mLooperVp = (ViewPager) findViewById(R.id.vpager_hotelpager_loopview);
        mTopLooperLay = (LinearLayout) findViewById(R.id.llay_homeitem_toppoint);
        mRedpoint = (ImageView)findViewById(R.id.iv_guide_redpoint);
        //推荐店铺
       mHorizontallay = (LinearLayout) findViewById(R.id.llay_horizontallay);
        horList = (HorizontalListView) findViewById(R.id.horizontallistview);
        adapter = new HorizontalListViewAdapter(HomeHotelActivity2.this,null);
        horList.setAdapter(adapter);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        viewpager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewpager);
        tabLayout.setupWithViewPager(viewpager);
    }
    private void setupViewPager(ViewPager viewPager) {
        Adapter adapter = new Adapter(getSupportFragmentManager());
        adapter.addFragment(new HomeTaocanFragment1(), "套餐");
        adapter.addFragment(new HomeAnliFragment1(), "案例");
        adapter.addFragment(new HomeBussinesFragment1(), "商家");
        viewPager.setAdapter(adapter);
    }
    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        refreshViewLay(HAVEDATA,mContentLay,mProgressLay,mNoNetLay);
        if (data instanceof HomeBotomListBean){
            HomeBotomListBean hotelData= (HomeBotomListBean) data;
            switch (hotelData.getResCode()){
                case "0000":
                    mhandler.sendEmptyMessage(LOOPERDATA);
                    break;
            }
        }else if(data instanceof  HomeHeaderLooperBean){
            HomeHeaderLooperBean looperData= (HomeHeaderLooperBean) data;
            switch (looperData.getResCode()) {
                case "0000":
                    looperDataDataListData = looperData.getData();
                    if (looperDataDataListData != null) {
                        setLooperView();
                    }
            }

        }else if (data instanceof GoodShopBean){
            GoodShopBean goodshopData= (GoodShopBean) data;
            switch (goodshopData.getResCode()){
                case "0000":
                    goodshopListData = goodshopData.getData();
                    if (goodshopListData.size()==0){
                        mHorizontallay.setVisibility(View.GONE);
                    }else{
                        adapter.append(goodshopListData);
                    }
                    break;
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
        switch (errorBean.getErrorCode()) {
            case ErrorBean.TIMEOUT:
                refreshViewLay(NONET,mContentLay,mProgressLay,mNoNetLay);
                break;
            case ErrorBean.NONET:
                refreshViewLay(NONET,mContentLay,mProgressLay,mNoNetLay);
                break;
            default:
                if(!isShowError){
                    CUtils.showDataErrToast(this);
                    isShowError=true;
                }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llay_header_back:
                this.finish();
            break;
            case R.id.lay_header_rightfunc:
                Intent intent = new Intent(this,ForSearchActivity.class);
                startActivity(intent);
                break;
        }
    }

    static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();
        public Adapter(FragmentManager fm) {
            super(fm);
        }
        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }
        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
        @Override
        public int getCount() {
            return mFragments.size();
        }
        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }
    /**
     * 获取数据;
     */
    private void getdata(){
        islogin = ((GlobalApplication) getApplication()).isLogin();
        if(islogin) {
            memBerId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        }
        getLoopdataFromNet(categoryId);
    }

    private void getLoopdataFromNet(int categoryId){
        /**
         * 广告轮播网路请求
         */
        String url= RequestCode.get_ProductServiceTopList;
        url += "&categoryID="+categoryId;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST,url,
                this, HomeHeaderLooperBean.class,RequestCode.get_ProductServiceTopList);
        HttpHandleUtil.executeCommonGet(this,httpRequestBean);
        /**
         * 店铺推广
         * http://s.66wedding.com/WeddingMobileApi/get_BusinessListByIsRecommendTwo?Token=00&category=1081&memberID=690
         * http://s.66wedding.com/WeddingMobileApi/get_BusinessListByIsRecommendTwo?Token=00&category=1081&memberID=690
         */
        String url2= RequestCode.get_BusinessListByIsRecommendTwo;
        url2 += "&category="+categoryId+"&memberID="+memBerId;
        HttpRequestBean httpRequestBean2 = new HttpRequestBean(RequestCode.GETREQUEST,url2,
                this, GoodShopBean.class,RequestCode.get_BusinessListByIsRecommendTwo);
        HttpHandleUtil.executeCommonGet(this,httpRequestBean2);
    }

    /**
     * 广告轮播设置;
     */
    public void setLooperView(){

        mTopLooperLay.removeAllViews();
        if(looperDataDataListData!=null ) {
            imgAdapter=new ImgAdapter();
            mLooperVp.setAdapter(imgAdapter);
            int firstViewitem=maxCount/2-(maxCount/2%looperDataDataListData.size());
            mLooperVp.setCurrentItem(firstViewitem);
            mhandler.removeCallbacksAndMessages(null);
            mhandler.sendEmptyMessageDelayed(TOPVIEWSCROLL,4000);
        }

        mPointList=new ArrayList<ImageView>();

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        ImageView imageView=null;
        mPointList.clear();
        for (int i = 0; i < looperDataDataListData.size(); i++) {
            imageView=new ImageView(this);
            imageView.setBackgroundResource(R.drawable.splash_graypoint_shape);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.dip2px(6),
                    DensityUtil.dip2px(6));
            if(i!=0) {
                params.leftMargin=DensityUtil.dip2px(6);
            }
            mPointList.add(imageView);
            mTopLooperLay.addView(imageView,params);
        }

        mLooperVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                position = position%looperDataDataListData.size();
                float redpointdx = distance * (position+positionOffset);
                int disten = (looperDataDataListData.size() - 1) * distance;
                RelativeLayout.LayoutParams params =
                        new RelativeLayout.LayoutParams(px, px);
                params.leftMargin= (int) redpointdx;
                if(redpointdx>disten) {
                    params.leftMargin= 0;
                }
                mRedpoint.setLayoutParams(params);
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if(state==ViewPager.SCROLL_STATE_DRAGGING) {
                    mhandler.removeCallbacksAndMessages(null);
                }else if(state==ViewPager.SCROLL_STATE_IDLE ){
                    mhandler.sendEmptyMessageDelayed(TOPVIEWSCROLL,4000);
                }else if(state==ViewPager.SCROLL_STATE_SETTLING){//相当于松手后
                    mhandler.removeCallbacksAndMessages(null);
                }

            }
        });
    }
    /**
     * 广告轮播
     */
    class ImgAdapter extends PagerAdapter {

        //设定Item数量
        @Override
        public int getCount() {
            return maxCount;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }
        /**
         * 初始化指定页视图对象
         * 1. 将指定下标对应的视图添加为container的子View
         * 2. 将视图返回
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            int index=position%looperDataDataListData.size();
            String nvc_picMain = looperDataDataListData.get(index).getNvc_PicMain();

            ImageView imgView = new ImageView(HomeHotelActivity2.this);
            x.image().bind(imgView,nvc_picMain, ImageOptionsUtil.getOptions316_720());

            if(imgView.getParent()==null){
                container.addView(imgView, 0);
            }else{
                ((ViewGroup)imgView.getParent()).removeView(imgView);
                container.addView(imgView);
            }

            imgView.setTag(index);
            imgView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int index = (int) v.getTag();
                    int i_id =  looperDataDataListData.get(index).getI_Id();

                    Intent intent = new Intent(HomeHotelActivity2.this, HomeProductdetailActivity.class);
                    intent.putExtra("productId",i_id);
                    HomeHotelActivity2.this.startActivity(intent);

                }
            });

            return imgView;
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
        }
    }


    protected static final int HAVEDATA=1;
    protected static final int NODATA=0;
    protected static final int DATAERROR=2;
    protected static final int NONET=4;

    Handler mhandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case TOPVIEWSCROLL:
                    int currentItem = mLooperVp.getCurrentItem();
                    mLooperVp.setCurrentItem(++currentItem);
                    mhandler.sendEmptyMessageDelayed(TOPVIEWSCROLL,4000);
                    break;
            }
        }
    };

    public void refreshViewLay(int state, View mContentLay, View mProgressLay, View mNonetLay){
        switch (state) {
            case HAVEDATA:
                mProgressLay.setVisibility(View.GONE);
                if(mContentLay.isShown()) {
                    return;
                }else{
                    mContentLay.setVisibility(View.VISIBLE);
                }
                mProgressLay.setVisibility(View.GONE);
                mNonetLay.setVisibility(View.GONE);
                break;
            case NODATA:
                mProgressLay.setVisibility(View.VISIBLE);
                mContentLay.setVisibility(View.GONE);
                mNonetLay.setVisibility(View.GONE);
                break;
            case NONET:
                mProgressLay.setVisibility(View.GONE);
                mContentLay.setVisibility(View.GONE);
                mNonetLay.setVisibility(View.VISIBLE);
                break;
        }
    }
    //获取id
    public int getCategoryId() {
        return categoryId;
    }
}
